package me.eleme.anubis.openapi.oauth;



import lombok.extern.slf4j.Slf4j;
import me.eleme.anubis.openapi.config.Constants;
import me.eleme.anubis.openapi.config.oauth.response.ErrorResponse;
import me.eleme.anubis.openapi.utils.Base64Util;
import me.eleme.anubis.openapi.utils.EleHashMap;

import java.util.Map;
import java.util.UUID;

/**
 * @param <T> 基础认证请求实体
 * @author liuzhiyong
 */
@Slf4j
public abstract class BaseOauthRequest<T extends ErrorResponse> implements OauthRequest<T> {

    /**
     * HTTP请求头参数
     */
    protected Map<String, String> headerMap;
    /**
     * HTTP Body参数
     */
    protected Map<String, String> bodyMap;
    /**
     * 自定义表单参数
     */
    protected EleHashMap customParams;

    protected void setAuthorization(String appKey, String appSecret, String sign) {
        String headOauthKey = Constants.HEAD_OAUTH_KEY;
        this.putHeaderParam(headOauthKey, this.getBasic(appKey, appSecret), sign);
    }

    public void putHeaderParam(String key, String value, String sign) {
        if (headerMap == null) {
            headerMap = new EleHashMap();
        }
        this.headerMap.put(key, value);
        String reqId = getReqId();
        this.headerMap.put("x-eleme-requestid", reqId);
        log.info("{} request id is:{}", sign, reqId);
    }

    public void putBodyParam(String key, String value) {
        if (bodyMap == null) {
            bodyMap = new EleHashMap();
        }
        this.bodyMap.put(key, value);
    }

    private String getBasic(String appKey, String appSecret) {
        StringBuilder sb = new StringBuilder();
        StringBuilder basicContent = new StringBuilder();
        basicContent.append(appKey).append(":").append(appSecret);
        String encodeToString = Base64Util.encode(basicContent.toString().getBytes());
        sb.append("Basic").append(" ").append(encodeToString);
        return sb.toString();
    }

    private static String getReqId() {
        String rid;
        try {
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            if (uuid.length() > Constants.UUID_MAX_LENGTH) {
                uuid = uuid.substring(0, 32);
            }
            rid = uuid.toUpperCase();
        } catch (Exception e) {
            rid = "00112233445566778899AABBCCDDEEFF";
        }
        return rid + "|" + System.currentTimeMillis();
    }

}
